const path = require('path')
const Koa = require('koa')
const cors = require('koa2-cors')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koaStatic = require('koa-static')
const setAssociations = require('./db/setAssociations')

// 路由引入
const userRouter = require('./routes/user')
const trainRouter = require('./routes/train')
const exerciseRouter = require('./routes/exercise')
const circlesRouter = require('./routes/circles')
const sharedRouter = require('./routes/shared')

const app = new Koa()

// 允许跨域
app.use(cors())

// koa-onerror handler
onerror(app)

app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

app.use(koaStatic(path.join(__dirname, 'public'))) // 静态资源目录
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles'))) // 上传的文件存储目录

// 路由注册
app.use(userRouter.routes(), userRouter.allowedMethods()) // 用户
app.use(trainRouter.routes(), trainRouter.allowedMethods()) // 训练课程
app.use(exerciseRouter.routes(), exerciseRouter.allowedMethods()) // 运动
app.use(circlesRouter.routes(), circlesRouter.allowedMethods()) // 圈子
app.use(sharedRouter.routes(), sharedRouter.allowedMethods()) // 共享

// 错误处理
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

// 为 Sequelize 模型设置关联关系
setAssociations()

module.exports = app
